package net.loststone.dao

import org.springframework.beans.factory.InitializingBean
import com.mongodb.Mongo
import com.mongodb.DBCollection
import com.mongodb.DBObject
import com.mongodb.BasicDBObject

class TodoService implements InitializingBean {

    private static final String NOM_DB = "patopay"
    private static final String NOM_COLLECIO = "todos"

    Mongo mongoDb;
    DBCollection todosCollection;

    static transactional = true

    // inicialitzacio
    void afterPropertiesSet() {
        mongoDb = new Mongo();
        def db = mongoDb.getDB(NOM_DB)
        todosCollection = db.getCollection(NOM_COLLECIO)
        println "Inicialitzat todo service"
    }

    def afegirTodo(DBObject doc) {
        // TODO mirar que no hi sigui (key -> nom, descripcio
        DBObject query = new BasicDBObject()
        query.put("nom", doc.get("nom"))
        query.put("descripcio", doc.get("descripcio"))
        if (null == todosCollection.findOne(query)) {
            // vol dir que no hi era.
            todosCollection.insert(doc);
        }

    }

    def modificarTodo(DBObject doc) {
        todosCollection.save(doc)
    }

    def agafarTodos() {
        return todosCollection.find().toArray();
    }
}
